//
//  ViewController.m
//  InterViewQuestions
//
//  Created by flannery on 2020/2/19.
//  Copyright © 2020 flannery. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self test5];
}

- (void)test{
    dispatch_queue_t serialQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
    NSLog(@"1");
    dispatch_async(serialQueue, ^{
        NSLog(@"2");
    });
    NSLog(@"3");
    dispatch_sync(serialQueue, ^{
        NSLog(@"4");
    });
    NSLog(@"5");
}


- (void)test2{
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        [self performSelector:@selector(test2___) withObject:nil afterDelay:5];
    });
}

- (void)test2___{
    NSLog(@"test2-__");
}

- (void)test3{
    dispatch_queue_t concurrentQueue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
    
    for (NSInteger i = 0; i < 10; i++) {
        dispatch_sync(concurrentQueue, ^{
            NSLog(@"%zd",i);
        });
    }
    
    dispatch_barrier_sync(concurrentQueue, ^{
        NSLog(@"barrier");
    });
    
    for (NSInteger i = 10; i<20; i++) {
        dispatch_sync(concurrentQueue, ^{
            NSLog(@"%zd",i);
        });
    }
    
    
}

- (void)test4{
    //保持线程同步
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSInteger number = 0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        number = 100;
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    NSLog(@"semapore -- end, number - %zd", number);
}

- (void)test5{
    [Person shareInstance];
}

@end


@implementation Person

+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}


@end
